import {useImmerState} from '../../hooks/useImmerState';
import {addLesson, downLesson, listLesson, saveLesson} from '../../apis/course';
import useGlobal from '../../hooks/useGlobal';
import useDidMount from '../../hooks/useDidMount';

const useCourseListModel = (initialState = {
  list: []
}) => {
  const [state, setState] = useImmerState(initialState);
  const {state: globalState} = useGlobal();

  const getCourseList = async () => {
    const res = await listLesson(globalState.login?.token);
    setState(draft => {
      draft.list = res.data.list.map(item => ({...item, key: item.id}));
    });
  };

  const addCourse = async (course) => {
    const res = await addLesson(globalState.login?.token, course);
    if (res.code === 1) {
      setState(draft => {
        draft.list.push({...res.data, key: res.data.id});
      });
    }
  };

  const updateCourse = async (course, index) => {
    const res = await saveLesson(globalState.login?.token, course);
    if (res.code === 1) {
      setState(draft => {
        draft.list[index] = {...draft.list[index], ...course};
      });
    }
  };

  const removeCourse = async (course, index) => {
    const res = await downLesson(globalState.login?.token, course.id);
    if (res.code === 1) {
      setState(draft => {
        draft.list[index].status = 0;
      });
    }
  };

  const effect = {
    getCourseList,
    addCourse,
    updateCourse,
    removeCourse
  };

  useDidMount(() => {
    getCourseList();
  });

  return {
    state,
    effect
  };
};

export default useCourseListModel;